# -*- coding: utf-8 -*-
import jsonpath
from abc import abstractmethod

from codes.hjt_assertion.assert_expr import AssertExpr


class BasicExtract:
    def __init__(self, case_data, response_data):
        """
        :param case_data: yaml用例数据
        :param response_data: 响应数据
        """
        self.case_data = case_data
        self.suffix_request_args = case_data.get('request')
        self.response_data = response_data.json()
        self.extract_to_file = self.case_data.get('extract_to_file')
        self.extract_to_class = self.case_data.get('extract_to_class')
        self.extract_to_module = self.case_data.get('extract_to_module')

    def _parse_variable(self, variable_val: str):
        """
        解析变量表达式
        :param variable_val: e.g. $..id、$request.name、$len($request.name[2])、$func1($request.fields[0], 1)
        :return: 解析后的结果
        """
        variable_val = variable_val.strip()
        if variable_val.startswith(('$.',)):
            # jsonpath解析规则
            real_val = jsonpath.jsonpath(self.response_data, variable_val)[0]
        else:
            # 其他解析规则
            real_val = AssertExpr(variable_val, self.suffix_request_args, self.response_data).main()
        return real_val

    @abstractmethod
    def _save_variable(self, name: str, val: str, extract_type: str):
        """
        保存变量
        :param name: 变量别名
        :param val: 变量值
        :param extract_type: 提取类型
        :return: None
        """
        pass

    @abstractmethod
    def main(self):
        """
        不同的提取类型处理
        :return: None
        """
        pass
